<?php

namespace App\Http\Requests\Cart;

use App\Http\Requests\ApiRequest;
use App\Models\Cart\Cart;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\Guard;
use Illuminate\Validation\Validator;

/**
 * @property string cart_id
 * @property string quantity
 */
class CartUpdateRequest extends ApiRequest
{
    use ApiChecker, ProductOptionRequest;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'language'      => 'required|string|max:' . self::MAX_STRING,
            'store_id'      => 'nullable|int|min:0|max:' . self::MAX_INT,
            'quantity'      => 'required|int|min:1|max:'. self::MAX_INT,
        ];
    }

    /**
     * @param Validator $validator
     * @throws \Exception
     */
    public function afterValidator(Validator $validator)
    {
        $cart_id = $this->cart;

        $cart = $this->getCart($cart_id);

        $this->option = $cart->option;
        $this->product_id = $cart->product_id;
//        $this->quantity = '';

//        $this->checkProductExist();
        $this->checkProductQuantity();
        $this->checkProductOptions();

        $this->cart = $cart;
    }

    /**
     * @param $cart_id
     * @return mixed
     * @throws \Exception
     */
    private function getCart($cart_id)
    {
        $cart = Cart::memoWhereFirst(['cart_id' => $cart_id, 'customer_id' => Guard::customer()->customer_id]);

        $this->checkItemExist($cart);

        return $cart;
    }
}
